import 'package:flutter/material.dart';
import 'side_menu_controller.dart';
import 'menu_item_model.dart';
import 'menu_level_two.dart';

class MenuLevelOne extends StatefulWidget {
  final MenuItemModel menuItem;
  final Color selectedColor;
  final Color hoverColor;
  final Color textColor;
  final Color selectedTextColor;
  final SideMenuController controller;
  final bool isCollapsed;
  
  const MenuLevelOne({
    super.key,
    required this.menuItem,
    required this.selectedColor,
    required this.hoverColor,
    required this.textColor,
    required this.selectedTextColor,
    required this.controller,
    this.isCollapsed = false,
  });

  @override
  State<MenuLevelOne> createState() => _MenuLevelOneState();
}

class _MenuLevelOneState extends State<MenuLevelOne> {
  bool isHovered = false;
  OverlayEntry? _overlayEntry;
  
  @override
  void dispose() {
    _removeOverlay();
    super.dispose();
  }
  
  void _removeOverlay() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }
  
  void _showSubmenuOverlay(BuildContext context) {
    if (!widget.menuItem.hasChildren || !widget.isCollapsed) return;
    
    final RenderBox renderBox = context.findRenderObject() as RenderBox;
    final position = renderBox.localToGlobal(Offset.zero);
    
    _overlayEntry = OverlayEntry(
      builder: (context) {
        return Positioned(
          left: widget.isCollapsed ? 80 : 250,
          top: position.dy,
          child: Material(
            elevation: 4.0,
            borderRadius: BorderRadius.circular(4),
            child: Container(
              width: 200,
              decoration: BoxDecoration(
                color: const Color(0xFF374A5E),
                borderRadius: BorderRadius.circular(4),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.2),
                    blurRadius: 5,
                    offset: const Offset(0, 3),
                  ),
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: widget.menuItem.children.map((subItem) {
                  return MenuLevelTwo(
                    menuItem: subItem,
                    selectedColor: widget.selectedColor,
                    hoverColor: widget.hoverColor,
                    textColor: widget.textColor,
                    selectedTextColor: widget.selectedTextColor,
                    controller: widget.controller,
                    isCollapsed: false, // 在弹出菜单中显示完整内容
                  );
                }).toList(),
              ),
            ),
          ),
        );
      },
    );
    
    Overlay.of(context).insert(_overlayEntry!);
  }

  @override
  Widget build(BuildContext context) {
    final isExpanded = widget.controller.isLevelOneExpanded(widget.menuItem.id);
    final isSelected = widget.controller.isMenuItemSelected(widget.menuItem.id);
    
    return Column(
      children: [
        // 一级菜单项
        MouseRegion(
          onEnter: (event) {
            setState(() {
              isHovered = true;
            });
            if (widget.isCollapsed && widget.menuItem.hasChildren) {
              _showSubmenuOverlay(context);
            }
          },
          onExit: (event) {
            setState(() {
              isHovered = false;
            });
            if (widget.isCollapsed) {
              _removeOverlay();
            }
          },
          child: _buildMenuItemContent(isSelected, isExpanded),
        ),
        
        // 二级菜单容器 - 仅在非折叠状态下显示
        if (widget.menuItem.hasChildren && !widget.isCollapsed)
          AnimatedContainer(
            duration: const Duration(milliseconds: 300),
            height: isExpanded ? widget.menuItem.children.length * 40.0 : 0,
            curve: Curves.easeInOut,
            child: SingleChildScrollView(
              physics: const NeverScrollableScrollPhysics(),
              child: Column(
                children: widget.menuItem.children.map((subItem) {
                  return MenuLevelTwo(
                    menuItem: subItem,
                    selectedColor: widget.selectedColor,
                    hoverColor: widget.hoverColor,
                    textColor: widget.textColor,
                    selectedTextColor: widget.selectedTextColor,
                    controller: widget.controller,
                    isCollapsed: widget.isCollapsed,
                  );
                }).toList(),
              ),
            ),
          ),
      ],
    );
  }

  // 提取菜单项内容为单独方法，避免代码重复
  Widget _buildMenuItemContent(bool isSelected, bool isExpanded) {
    // 定义颜色，确保悬停颜色足够明显
    final effectiveHoverColor = Color.lerp(widget.hoverColor, widget.selectedColor, 0.3);
    
    return InkWell(
      onTap: () {
        if (widget.menuItem.hasChildren) {
          if (!widget.isCollapsed) {
            widget.controller.toggleLevelOne(widget.menuItem.id);
          }
          // 折叠状态下点击有子菜单的菜单项不做任何操作，依靠悬停事件显示子菜单
        } else {
          // 只有菜单项没有子菜单时才选择它
          widget.controller.selectMenuItem(widget.menuItem.id, route: widget.menuItem.route);
        }
      },
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 150),
        decoration: BoxDecoration(
          color: isSelected 
              ? widget.selectedColor 
              : (widget.isCollapsed && widget.menuItem.hasChildren && widget.controller.hasSelectedChild(widget.menuItem))
                ? widget.selectedColor // 折叠模式下，如果有子菜单被选中，显示淡色背景
                : (isHovered ? effectiveHoverColor : null),
          border: isHovered && !isSelected && !(widget.isCollapsed && widget.menuItem.hasChildren && widget.controller.hasSelectedChild(widget.menuItem))
              ? Border(
                  left: BorderSide(
                    color: widget.selectedColor,
                    width: 3,
                  ),
                )
              : null,
        ),
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
        width: double.infinity,
        child: widget.isCollapsed 
            ? Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    widget.menuItem.icon,
                    color: isSelected ? widget.selectedTextColor : widget.textColor,
                    size: 20,
                  ),
                  const SizedBox(height: 4),
                  Text(
                    widget.menuItem.title,
                    style: TextStyle(
                      fontSize: 10,
                      color: isSelected ? widget.selectedTextColor : widget.textColor,
                      fontWeight: isSelected || isHovered || widget.controller.hasSelectedChild(widget.menuItem)
                          ? FontWeight.bold 
                          : FontWeight.normal,
                    ),
                    overflow: TextOverflow.ellipsis,
                    textAlign: TextAlign.center,
                  ),
                ],
              )
            : Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Icon(
                    widget.menuItem.icon,
                    color: isSelected ? widget.selectedTextColor : widget.textColor,
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      widget.menuItem.title,
                      style: TextStyle(
                        color: isSelected ? widget.selectedTextColor : widget.textColor,
                        fontWeight: isSelected || isHovered || widget.controller.hasSelectedChild(widget.menuItem)
                            ? FontWeight.bold 
                            : FontWeight.normal,
                      ),
                    ),
                  ),
                  if (widget.menuItem.hasChildren)
                    Icon(
                      isExpanded ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                      color: isSelected ? widget.selectedTextColor : widget.textColor,
                    ),
                ],
              ),
      ),
    );
  }
}